import enquireJs from 'enquire.js'
import {
  roleOptions
} from './options.js'
import moment from 'moment'
// import { fi } from 'date-fns/locale'

export function isDef (v) {
  return v !== undefined && v !== null
}

/**
 * Remove an item from an array.
 */
export function remove (arr, item) {
  if (arr.length) {
    const index = arr.indexOf(item)
    if (index > -1) {
      return arr.splice(index, 1)
    }
  }
}

export function repeatNum (str, a) {
  let b = str.indexOf(a)
  var num = 0
  while (b !== -1) {
    num++
    b = str.indexOf(a, b + 1)
  }
  return num
}
export function isRegExp (v) {
  return _toString.call(v) === '[object RegExp]'
}

// 媒体查询
export function enquireScreen (call) {
  const handler = {
    match: function () {
      call && call(true)
    },
    unmatch: function () {
      call && call(false)
    }
  }
  enquireJs.register('only screen and (max-width: 767.99px)', handler)
}

const _toString = Object.prototype.toString

/**
 * Base64编码
 */
export function getBase64 (file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader()
    reader.readAsDataURL(file)
    reader.onload = () => resolve(reader.result)
    reader.onerror = (error) => reject(error)
  })
}

/**
 * 根据角色类型返回可选择的角色类型列表
 */
export function getRoleTypeOptions (roleType) {
  const role = [...roleOptions]
  const outsideType = ['3', '4', '5', '6']
  if (outsideType.includes(roleType)) {
    if (roleType === '3') {
      return Object.freeze(
        role.filter((d) => ['4', '5', '6'].includes(d.value))
      )
    } else if (roleType === '4') {
      return Object.freeze(role.filter((d) => ['6'].includes(d.value)))
    } else if (roleType === '5') {
      return Object.freeze(role.filter((d) => ['6'].includes(d.value)))
    } else {
      return Object.freeze([])
    }
  }
  return Object.freeze(role)
}

/**
 * 文本加星
 */
export function starTxt (txt) {
  if (txt) {
    const among = []
    let prefix = 3
    let suffix = 3
    if (txt.length === 1) {
      prefix = 0
      suffix = 0
    } else if (txt.length === 2) {
      prefix = 1
      suffix = 0
    } else if (txt.length <= 6) {
      prefix = 1
      suffix = 1
    }
    for (let i = 0; i < txt.length - (prefix + suffix); i++) among.push('*')
    return `${this.data.phone.substr(0, prefix)}${among.join(
      ''
    )}${this.data.phone.substr(-suffix, suffix)}`
  }
  return ''
}

/**
 * 去空格
 */
export function trimSpace (obj, key, value) {
  if (typeof value === 'string') {
    const trim = obj[key].replaceAll(' ', '')
    if (trim !== value) {
      obj[key] = trim
    }
  }
}

/**
 * dataUrl 转 file
 */
export function dataURLtoFile (dataurl, fileName) {
  var arr = dataurl.split(',')
  var mime = arr[0].match(/:(.*?);/)[1]
  var bstr = atob(arr[1])
  var n = bstr.length
  var u8arr = new Uint8Array(n)
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n)
  }
  return new File([u8arr], fileName, {
    type: mime
  })
}

// 时间格式化
export function momentTime (time, format) {
  return moment(time, format)
}

// changeHourMinutestr
export function changeHourMinutestr (str) {
  if (str !== '0' && str !== '' && str !== null) {
    return (
      parseInt(Math.floor(str / 60).toString() / 24) +
      '天' +
      (+Math.floor(str / 60).toString() -
        parseInt(Math.floor(str / 60).toString() / 24) * 24) +
      '小时' +
      ((str % 60).toString().length < 2
        ? '0' + (str % 60).toString()
        : (str % 60).toString()) +
      '分'
    )
  } else {
    return ''
  }
}

export function downloadIamge (src, imgName) {
  var canvas = document.createElement('canvas')

  var img = document.createElement('img')
  img.onload = function (e) {
    canvas.width = img.width
    canvas.height = img.height

    var context = canvas.getContext('2d')
    context.drawImage(img, 0, 0, img.width, img.height)
    canvas.getContext('2d').drawImage(img, 0, 0, img.width, img.height)
    canvas.toBlob((blob) => {
      var link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      link.download = imgName
      link.click()
    }, 'image/jpeg')
  }
  img.crossOrigin = 'Anonymous'
  img.src = src
}
// 数字前三后四中间打点 eg. 220****426
export function numAsteriskFormat (num) {
  if (num) {
    num = num + ''
    let str = ''
    for (let i = 0; i < num.length - 7; i++) {
      str += '*'
    }
    return num.substr(0, 3) + str + num.substr(num.length - 4)
  }
}

export function downLoads (filename, content) {
  // filename 文件名，content 下载的内容
  var aLink = document.createElement('a')
  var blob = new Blob([content], {
    type: 'application/vnd.ms-excel' // 文件类型
  })

  aLink.download = filename

  aLink.href = URL.createObjectURL(blob)

  aLink.click()

  URL.revokeObjectURL(blob)
}

export function downLoadsV2 (fileName, fileUrl) {
  console.log(fileName, fileUrl)
  const link = document.createElement('a')
  link.href = fileUrl
  link.download = fileName // 可根据需要自定义下载后的文件名，也可以省略这行让浏览器按服务器返回的原始文件名处理
  document.body.appendChild(link)
  link.click()
  document.body.removeChild(link)
}

// 枚举转换
export function arrData (value, data, symbol, type) {
  const params = []
  value.forEach((element) => {
    data.forEach((ele) => {
      if (type === 'string') {
        if (element === ele.value) {
          params.push(ele.label)
        }
      } else {
        if (+element === +ele.value) {
          params.push(ele.label)
        }
      }
    })
  })
  return params.join(symbol)
}

// 时间格式到分
export function formattingMinute (time) {
  if (time) {
    return time.substring(0, 16)
  } else {
    return '-'
  }
}
export function formattingDay (time) {
  if (time) {
    return time.substring(0, 10)
  } else {
    return '-'
  }
}
export function desensitization (str) {
  if (str) {
    var pat = /(\d{3})\d*(\d{4})/
    var b = str.replace(pat, '$1****$2')
    return b
  } else {
    return '-'
  }
}
// 钱分转元
export function formattingMoney (str) {
  if (str) {
    var b = (+str).toFixed(2)
    return b + '元'
  } else {
    return '0.00元'
  }
}

export function formattingMoney1 (str) {
  if (str) {
    var b = (+str).toFixed(2)
    return b
  } else {
    return '0.00'
  }
}

export function formattingFixed (str) {
  if (str) {
    var b = (+str).toFixed(2)
    return b
  } else {
    return '0.00'
  }
}
// 反向查找
export function getParent (data2, id, children = 'children', level = 0) {
  var arrRes = []

  const obj = {
    id: 0,

    [children]: data2
  }

  const rev = (data, id, level) => {
    if (!data || !data[children] || !data[children].length) {
      return
    }

    for (var i = 0; i < data[children].length; i++) {
      const item = data[children][i]

      if (item.id === id) {
        // 将匹配到的结果保存到数组

        arrRes.unshift({
          level,
          activeId: item.id,
          name: item.name
        })

        // 递归它的父级

        rev(obj, data.id, 0)

        break
      } else if (item[children] && item[children].length > 0) {
        // 如果有子集，则把子集作为参数重新执行本方法

        rev(item, id, level + 1)
      }
    }
  }

  rev(obj, id, level)

  return arrRes
}
// 1.获取当前的日期时间 格式“yyyy-MM-dd HH:MM:SS”
function p (s) {
  return s < 10 ? '0' + s : s
}
export function GetNowTime () {
  var myDate = new Date()
  // 获取当前年
  var year = myDate.getFullYear()
  // 获取当前月
  var month = myDate.getMonth() + 1
  // 获取当前日
  var date = myDate.getDate()
  var h = myDate.getHours() // 获取当前小时数(0-23)
  var m = myDate.getMinutes() // 获取当前分钟数(0-59)
  var s = myDate.getSeconds()
  return (
    year + '-' + p(month) + '-' + p(date) + ' ' + p(h) + ':' + p(m) + ':' + p(s)
  )
}

export function GetNowDay () {
  var myDate = new Date()
  // 获取当前年
  var year = myDate.getFullYear()
  // 获取当前月
  var month = myDate.getMonth() + 1
  // 获取当前日
  var date = myDate.getDate()

  return (
    year + '/' + p(month) + '/' + p(date)
  )
}
//  获取当前日期前后多少天的日期，之前多少天传正数，后面多少天传负数，今天传0，
//  num为传入的数字， time为传入的指定日期，如果time不传，则默认为当前时间
export function funDate (num, time) {
  const n = num
  let d = ''
  if (time) {
    d = new Date(time)
  } else {
    d = new Date()
  }
  let year = d.getFullYear()
  let mon = d.getMonth() + 1
  let day = d.getDate()
  if (day <= n) {
    if (mon > 1) {
      mon = mon - 1
    } else {
      year = year - 1
      mon = 12
    }
  }
  d.setDate(d.getDate() - n)
  year = d.getFullYear()
  mon = d.getMonth() + 1
  day = d.getDate()
  const s = year + '/' + (mon < 10 ? ('0' + mon) : mon) + '/' + (day < 10 ? ('0' + day) : day)
  return s
}
// 千分符
export function thousandBitSeparator (num) {
  num = (num || 0).toString()
  let number = 0
  let floatNum = ''
  let intNum = ''
  // 判断是否有小数位，有则截取小数点后的数字
  if (num.indexOf('.') > 0) {
    number = num.indexOf('.') // 获取小数点出现的位置
    floatNum = num.substr(number) // 截取arr.substr(form, length)
    intNum = num.substring(0, number) // 截取arr.substring(start, end)
  } else {
    intNum = num
  }
  const result = []
  let counter = 0
  intNum = intNum.split('')
  // 利用3的倍数，向数组插入','
  for (let i = intNum.length - 1; i >= 0; i--) {
    counter++
    result.unshift(intNum[i])
    if (!(counter % 3) && i !== 0) {
      result.unshift(',')
    }
  }
  return result.join('') + floatNum || ''
}

export function debounce (fn, timerDelay, immediate) {
  let timer
  return function () {
    const that = this
    const args = arguments

    if (timer) clearTimeout(timer)
    if (immediate) {
      var callNow = !timer
      timer = setTimeout(() => {
        timer = null
      }, timerDelay)
      if (callNow) fn.apply(that, args)
    } else {
      timer = setTimeout(function () {
        fn.apply(that, args)
      }, timerDelay)
    }
  }
}

// // 倒计时
// export function countdown(totalSeconds) {
//   return new Promise((resolve, reject) => {
//     const countdown = setInterval(() => {
//       // 将秒数转换为分钟和剩余的秒数
//       minutes = Math.floor(totalSeconds / 60)
//       seconds = (totalSeconds % 60) < 10 ? '0' + totalSeconds % 60 : totalSeconds % 60
//       // 如果倒计时结束则清除定时器并返回结果
//       if (totalSeconds === 0) {
//         clearInterval(countdown)// 销毁定时器
//         resolve({
//           minutes: '00',
//           seconds: '00'
//         })// 用Promise向外部传递参数
//       }
//       // 每隔1秒秒数减1
//       totalSeconds--
//     }, 1000)
//   })
// }
